package com.siyoumi.app.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.app.entity.M2Attr;
import com.siyoumi.app.entity.M2AttrSku;
import com.siyoumi.app.mapper.M2AttrMapper;
import com.siyoumi.service.ServiceImplBase;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.util.XStr;
import org.springframework.stereotype.Service;

import java.util.List;


//t_m2_attr
@Service
public class M2AttrService
        extends ServiceImplBase<M2AttrMapper, M2Attr> {
    static public M2AttrService getBean() {
        return XSpringContext.getBean(M2AttrService.class);
    }

    public QueryWrapper<M2Attr> listQuery(String spuId) {
        return listQuery(spuId, null);
    }

    public QueryWrapper<M2Attr> listQuery(String spuId, String name) {
        QueryWrapper<M2Attr> query = q();
        query.eq("mattr_del", 0);

        if (XStr.hasAnyText(spuId)) { //商品ID
            query.eq("mattr_spu_id", spuId);
        }
        if (XStr.hasAnyText(name)) { //商品ID
            query.eq("mattr_name", name);
        }

        return query;
    }

    /**
     * 列表
     *
     * @param spuId
     */
    public List<M2Attr> getList(String spuId) {
        QueryWrapper<M2Attr> query = listQuery(spuId)
                .orderByAsc("mattr_order");

        return list(query);
    }

    /**
     * 数量
     *
     * @param spuId
     */
    public Long getCount(String spuId) {
        return getBaseMapper().selectCount(listQuery(spuId));
    }

    public XReturn delete(String id) {
        M2Attr entityAttr = getEntity(id);
        //标记删除
        M2Attr entityUpdate = new M2Attr();
        entityUpdate.setMattr_id(entityAttr.getKey());
        entityUpdate.setMattr_del(XDate.toS());
        updateById(entityUpdate);
        //删除规格属性
        M2AttrSkuService appAttrSku = M2AttrSkuService.getBean();
        List<M2AttrSku> list = appAttrSku.getList(null, id);
        list.forEach(item ->
        {
            appAttrSku.delete(item.getKey());
        });
        //删除所有sku
        M2SkuService.getBean().deleteBySpuId(entityAttr.getMattr_spu_id());

        return XReturn.getR(0);
    }


}
